package com.bw.myapply_module.myapply

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.bw.myapply_module.R
import com.bw.myapply_module.databinding.ActivityApplyBinding
import com.bw.myapply_module.myapply.adapter.ApplyAdapter
import com.bw.myapply_module.myapply.entity.ApplyEntity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.kf.common.mvi.view.BaseActivity
import com.kf.common.utils.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

@Route(path = "/apply/applyactivity")
class ApplyActivity : BaseActivity<ActivityApplyBinding, ApplyViewModel>(), View.OnClickListener,
    OnItemChildClickListener {

    lateinit var applyAdapter: ApplyAdapter
    lateinit var applyList: ArrayList<ApplyEntity>

    override fun createViewModel(): ApplyViewModel {
        return viewModels<ApplyViewModel>().value
    }

    override fun createViewBind(): ActivityApplyBinding {
        return ActivityApplyBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.setStatusBarColor(this, Color.parseColor("#2196F3"))
        initClick()
        initApplyRecycler()
        mViewModel.requestApplyAll()
        bindApply()
    }

    private fun initApplyRecycler() {
        mView.applyRecycler.layoutManager = LinearLayoutManager(this)
        applyAdapter = ApplyAdapter()
        applyAdapter.setOnItemChildClickListener(this)
        mView.applyRecycler.adapter = applyAdapter
    }

    private fun bindApply() {
        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.mutableContainer
                .uiStateFlow
                .collect {
                    if (it.entity != null) {
                        it.entity.values!!.forEach {
                            it.applyTime = DateUtils().dateUtils(it.applyTime.toString())
                        }
                        applyList = it.entity.values as ArrayList<ApplyEntity>
                        applyAdapter.setNewInstance(it.entity.values as ArrayList)
                    }
                }
        }
    }

    private fun initClick() {
        mView.applyBack.setOnClickListener(this)
        mView.applyAll.setOnClickListener(this)
        mView.applyData.setOnClickListener(this)
    }

    private var popupWindows: PopupWindow? = null
    private var isShow = false
    var calendar = Calendar.getInstance()

    @SuppressLint("NotifyDataSetChanged")
    override fun onClick(v: View?) {
        var id = v!!.id
        when (id) {
            R.id.apply_back -> {
                finish()
            }
            R.id.apply_all -> {
                var inflater = LayoutInflater.from(this).inflate(R.layout.apply_popwindow, null)
                var commit = inflater.findViewById<TextView>(R.id.apply_pop_commit)
                var reset = inflater.findViewById<TextView>(R.id.apply_pop_reset)
                reset.setOnClickListener {
                    mView.applyAll.setText("全部申请")
                    mView.applyAllType.setText("全部")
                    mView.applyData.setText("mm/dd/yyyy")
                    filtrateFun()
                    popupWindows!!.dismiss()
                    isShow = false
                }
                commit.setOnClickListener {
                    var radioLefts = inflater.findViewById<RadioGroup>(R.id.radio_left)
                    var leftButton =
                        inflater.findViewById<RadioButton>(radioLefts.checkedRadioButtonId)
                    var radioRights = inflater.findViewById<RadioGroup>(R.id.radio_right)
                    var rightButton =
                        inflater.findViewById<RadioButton>(radioRights.checkedRadioButtonId)
                    mView.applyAll.setText(leftButton.text.toString())
                    mView.applyAllType.setText(rightButton.text.toString())
                    filtrateFun()
                    popupWindows!!.dismiss()
                    isShow = false
                }
                if (popupWindows == null) {
                    popupWindows = PopupWindow(this)
                    popupWindows.apply {
                        popupWindows!!.width = WindowManager.LayoutParams.MATCH_PARENT
                        popupWindows!!.height = ConvertUtils.dp2px(450f)
                        popupWindows!!.contentView = inflater
                    }
                }
                window.attributes.alpha = 1f
                if (!isShow) {
                    popupWindows!!.showAsDropDown(v)
                    isShow = true
                } else {
                    popupWindows!!.dismiss()
                    isShow = false
                }
            }
            R.id.apply_all_type -> {

            }
            R.id.apply_data -> {
                val datePickerDialog = DatePickerDialog(
                    MyApplyAllActivity@ this,
                    object : DatePickerDialog.OnDateSetListener {
                        override fun onDateSet(
                            view: DatePicker?,
                            year: Int,
                            month: Int,
                            dayOfMonth: Int
                        ) {
                            val calender =
                                year.toString() + "年" + (month + 1) + "月" + dayOfMonth + "日"
                            mView.applyData.setText(calender)
                            filtrateFun()
                        }
                    },
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH)
                )
                datePickerDialog.show()
            }
        }
    }

    //筛选使用集合
    var applyLeftList: ArrayList<ApplyEntity> = ArrayList()

    //筛选数据方法
    @SuppressLint("NotifyDataSetChanged")
    fun filtrateFun() {
        applyLeftList.clear()
        var left = mView.applyAll.text.toString()
        var right = mView.applyAllType.text.toString()
        when (left) {
            "全部申请" -> {
                applyLeftList.addAll(applyList)
            }
            "维修" -> {

            }
            "来访" -> {
                applyList.forEach {
                    if (it.type == 0)
                        applyLeftList.add(it)
                }
            }
            "车位" -> {
                applyList.forEach {
                    if (it.type == 1)
                        applyLeftList.add(it)
                }
            }
        }

        var applyRightList = ArrayList<ApplyEntity>()
        when (right) {
            "全部" -> {
                applyLeftList.forEach {
                    if (it.state == 0)
                        applyRightList.add(it)
                }
            }
            "待提交" -> {

            }
            "待审核" -> {

            }
            "已通过" -> {
                applyLeftList.forEach {
                    if (it.state == 1)
                        applyRightList.add(it)
                }
            }
            "已驳回" -> {
                applyLeftList.forEach {
                    if (it.state == 3)
                        applyRightList.add(it)
                }
            }
            "审核中" -> {
                applyLeftList.forEach {
                    if (it.state == 2)
                        applyRightList.add(it)
                }
            }
        }

        var date = mView.applyData.text.toString()
        var applyFiltrateDate: ArrayList<ApplyEntity> = ArrayList()
        if (date != "mm/dd/yyyy") {
            applyRightList.forEach {
                if (it.applyTime == date) {
                    applyFiltrateDate.add(it)
                }
            }
        } else {
            applyFiltrateDate.addAll(applyRightList)
        }
        applyAdapter.data = applyFiltrateDate
        applyAdapter.notifyDataSetChanged()
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (view.id == R.id.item_come_next) {
            var applyAdapters = adapter as ApplyAdapter
            var data = applyAdapters.data
            if (data.get(position).type == 0) {
                ARouter.getInstance().build("/apply/applycomeactivity")
                    .withSerializable("applyEntity", data.get(position)).navigation()
            }
        }
    }
}